<?php


namespace api\web\controller;


use api\zmt\model\orderModel;
use api\zmt\model\RegistrationModel;
use api\zmt\validate\PayValidate;
use cmf\controller\RestBaseController;
use think\Exception;
use think\facade\Db;
use think\Request;

class payController extends RestBaseController
{
    //账户余额支付
    public function walletPay(Request $request)
    {
        $orderId = input('post.order_id');
        $order = orderModel::find($orderId);
        if (!$order){
            $this->error('订单不存在');
        }
        if ($order['status'] != 0){
            $this->error('该订单已支付');
        }
        //查询用户
        $user = RegistrationModel::find($request->userId);
        //判断账户余额是否够
        if ($user['money'] < $order['total_price']) {
            $this->error('账户余额不足');
        }
        Db::startTrans();
        $updateOrderStatus = false;
        $addMonerLog = true;
        $updateUserMoney = false;
        $type = 0;
        try {
            //1.订单的status修改成1
            $order -> status = 1;
            $order ->pay_type = '账户余额';
            $updateOrderStatus = $order->save();
            //2、流水记录
            $user = RegistrationModel::where('id', $order['user_id'])->find();
            if (!$user) {
                throw new Exception('用户不存在');
            }

            if ($type == 1){
                $after = $user['money'] + $order['total_price'];
            }
            if ($type == 0){
                $after = $user['money'] - $order['total_price'];
            }
            $data  = request()->post();
            $validate = new PayValidate();
            if (!$validate->scene('pay')->check($data)){
                return json(['code'=>'0','msg'=>$validate->getError(),'data'=>null]);
            }
            $primarmoney = RegistrationModel::find($request->userId);
            $pay = [
                'user_id' => $request->userId,
                'money' => $data['money'],
                'reason' => '商品购买',
                'before' => $primarmoney['wallet'],
                'after' => $after,
                'type' => $type,
                'create_time' => date('Y-m-d H:i:s'),
            ];
            if ($pay){
                return $after;
            }
            //3.用户余额修改
            $user -> money = $user['money'] -$order['total_price'];
            $updateUserMoney = $user->save();
            if ($updateOrderStatus && $addMonerLog && $updateUserMoney){
                Db::commit();
                return json(['status' => 'success', 'message' => '充值成功',]);
            }
        }catch (\Exception $exception) {

            $this->error($exception->getMessage());
            Db::rollback();
        }

    }

}